package com.xsp.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author xsp
 * @date 2024/1/20
 * @desc 动态代理--cglib模式
 */
public class ProxyFactory2 implements MethodInterceptor {
    public ProxyFactory2(Object target) {
        this.target = target;
    }

    private Object target;

    private Logger logger = LoggerFactory.getLogger(ProxyFactory2.class);

    public Object getProxyInstance() {
        // 创建工具类
        Enhancer enhancer = new Enhancer();
        // 设置目标对象为父类
        enhancer.setSuperclass(target.getClass());
        // 设置回调函数
        enhancer.setCallback(this);
        // 根据设置的父类创建子类, 即代理对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        try {
            logger.debug("cglib代理开始干活");
            // 执行目标对象的方法
            return method.invoke(target, objects);
        } catch (Exception e) {
            // 记录执行的错误信息
            logger.error("发生异常：{}", e.getCause().getMessage());
            throw e;
        }
    }
}